package com.zl.zsk.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zl.zsk.constant.RetCode;
import com.zl.zsk.exception.ImageCodeException;
import com.zl.zsk.exception.JwtInvalidException;
import com.zl.zsk.exception.NotLoginException;
import com.zl.zsk.pojo.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lxb
 * @version 1.0.0
 * @desc:
 * @date 2020-03-13 16:21
 */
public class HandleFailAuthentication implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("text/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        RetCode retCode;
        if(e instanceof ImageCodeException){
           retCode = RetCode.INVALIDE_CODE;
        }else if(e instanceof JwtInvalidException){
            retCode = RetCode.JWT_TOKEN_ERROR;
        }else if(e instanceof NotLoginException){
            retCode = RetCode.NOTLOGIN;
        }else{
            retCode = RetCode.USER_OR_PASSWORD_ERROR;
        }
        Result result = new Result(null,retCode.msg,false,retCode.code);
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
